package cn.lxb.web.starter.template;

import cn.lxb.web.starter.template.autoconfigure.config.ApplicationContextConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;

/**
 * 启动类
 *
 * @author 54lxb
 * @since 2019-11-20
 */
public abstract class AbstractStarter implements CommandLineRunner {

    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractStarter.class);

    @Override
    public void run(String... args) throws Exception {
        LOGGER.info("start server[port={}]", ApplicationContextConfig.getContext().getEnvironment().getProperty("server.port"));
    }

    /**
     * 构建API信息
     *
     * @return ApiInfo
     */
    protected ApiInfo apiInfo() {
        ApiInfoBuilder builder = new ApiInfoBuilder();
        builder.title(getServiceTitle());
        builder.description(getServiceDescription());
        builder.version(getServiceVersion());
        return builder.build();
    }

    /**
     * 设置分组及其扫描的包名
     *
     * @param groupName API分组的组名
     * @param basePackage  要扫描的包位置
     * @return Docket
     */
    protected Docket create(String groupName, String basePackage) {
        Docket docket = new Docket(DocumentationType.SWAGGER_2);
        docket.apiInfo(apiInfo());
        docket.groupName(groupName);
        docket.useDefaultResponseMessages(false);

        ApiSelectorBuilder selectorBuilder = docket.select();

        selectorBuilder.apis(RequestHandlerSelectors.basePackage(basePackage));
        selectorBuilder.paths(PathSelectors.any());
        selectorBuilder.build();

        return docket;
    }

    /**
     * 获取API标题
     *
     * @return API标题
     */
    protected String getServiceTitle() {
        return null;
    }

    /**
     * 获取API描述
     *
     * @return API描述
     */
    protected String getServiceDescription() {
        return null;
    }

    /**
     * 获取API版本号
     *
     * @return API版本号
     */
    protected String getServiceVersion() {
        return "1.0";
    }

}
